// import { getUserInfo } from './utils/utils'
import config from './config'
/**
  *
  * @param {String} url 接口
  * @param {Object} data 参数
  * @param {String} method 方法
  * @param {Boolean} isHideToast 是否隐藏toast，默认为false
  */
export default async function request({
  url,
  data = {},
  method = 'GET',
  ContentType = 'application/x-www-form-urlencoded',
  isNoToken = false,
  isHideToast = false,
  isShowModal = false,
  isShowLogin = true,
  _resolve = null
}) {
  const options = {
    url,
    data,
    method,
    ContentType,
    isNoToken,
    isHideToast,
    isShowModal,
    _resolve
  }
  if (!url) {
    throw new Error('url不能为空')
  }
  // if (!isNoToken) {
  //   try {
  //     await getUserInfo(isShowLogin)
  //   } catch (e) {
  //     console.log(e)
  //     throw new Error('未授权登录')
  //   }
  // }
  const token = wx.getStorageSync('token')
  const header = {
    'Content-Type': ContentType,
  }
  if (token) {
    header['Authorization'] = `${token}`
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      data,
      method,
      header,
      success: res => {
        const { status, msg ,data} = res.data
        if(status==99){
          showToast(msg||'登录过期')
          wx.clearStorageSync()
          return  wx.reLaunch({
            url:'/pages/login/login'
          })
        }

        if (status != 1) {
          showToast(msg||'连接超时')
          return reject(msg||'连接超时')
        } 
        
        resolve(data)
      },
      fail: err => {
        if (!isHideToast) {
          showToast('连接超时')
          setTimeout(() => {
            wx.hideLoading()
          }, 1000)
        }
        reject(err)
      }
    })
  })
  function showToast(text) {
    wx.showToast({
      icon: 'none',
      title: text || '请求异常',
    })
  }
  function showModal(text) {
    wx.showModal({
      title: '提示',
      content: text,
      success: (res) => {
        if (res.confirm) { }
      },
      showCancel: false
    })
  }
}
